package com.wwtech.epp.ui.activity.login.presenter;

import android.Manifest;
import android.content.DialogInterface;
import android.support.annotation.NonNull;

import com.ninjia.ninjiabaselibrary.utils.SpUtil;
import com.ninjia.ninjiabaselibrary.utils.VersionUtil;
import com.socks.library.KLog;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.contain.ContainValue;
import com.wwtech.epp.data.api.HttpAPIWrapper;
import com.wwtech.epp.entity.Token;
import com.wwtech.epp.entity.UserInfo;
import com.wwtech.epp.entity.UserLogin;
import com.wwtech.epp.ui.activity.login.SplashActivity;
import com.wwtech.epp.ui.activity.login.contract.SplashContract;
import com.wwtech.epp.utils.ToastUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.login
 * @Description: presenter of SplashActivity
 * @date 2017/08/01 16:44:18
 */
public class SplashPresenter implements SplashContract.SplashContractPresenter {

    HttpAPIWrapper httpAPIWrapper;
    private final SplashContract.View mView;
    private CompositeDisposable mCompositeDisposable;
    private SplashActivity mActivity;

    private static final int JUMPTOMAIN = 0;
    private static final int JUMPTOLOGIN = 1;
    private static final int HASPUDATE = 3;
    private boolean getLastVersionBack = false;
    private static int permissionState = -1;    //-1表示原始状态,0表示允许,1表示拒绝.
    private boolean hasUpdate = false;
    private boolean timeOver = false;
    private int jump = JUMPTOLOGIN;
    private boolean jumpToGuest = false;

    @Inject
    public SplashPresenter(@NonNull HttpAPIWrapper httpAPIWrapper, @NonNull SplashContract.View view, SplashActivity activity) {
        mView = view;
        this.httpAPIWrapper = httpAPIWrapper;
        mCompositeDisposable = new CompositeDisposable();
        this.mActivity = activity;
    }

    @Override
    public void subscribe() {

    }

    @Override
    public void unsubscribe() {
        if (!mCompositeDisposable.isDisposed()) {
            mCompositeDisposable.dispose();
        }
    }

    @Override
    public void observeJump() {
        Observable.interval(0, 1, TimeUnit.SECONDS).take(4)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) throws Exception {
                        return 2 - aLong;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())//发射用的是observeOn
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        KLog.i("1");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        KLog.i("2");
                    }

                    @Override
                    public void onNext(@NonNull Long remainTime) {
                        KLog.i("剩余时间" + remainTime);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        KLog.i("4");
                    }

                    @Override
                    public void onComplete() {
//                        jump = JUMPTOGUEST;
                        timeOver = true;
                        KLog.i("时间到，开始跳转");
                        if (permissionState != 0) {
                            return;
                        }
                        if (hasUpdate) {
                            return;
                        }
                        if (jumpToGuest) {
                            mView.iumpToGuest();
                            return;
                        }
                        if (jump == JUMPTOMAIN) {
                            mView.loginSuccees();
                        } else if (jump == JUMPTOLOGIN) {
                            mView.jumpToLogin();
                        }
                    }
                });
    }

    @Override
    public void getPermission() {
        AndPermission.with(mActivity)
                .requestCode(101)
                .permission(
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.CAMERA,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.INTERNET
                )
                .rationale((requestCode, rationale) -> {
                            AndPermission
                                    .rationaleDialog(mActivity, rationale)
                                    .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            ToastUtil.show(mActivity, "权限申请失败,app部分功能将无法使用!!!");
                                            if (jumpToGuest) {
                                                mView.iumpToGuest();
                                                return;
                                            }
                                            if (jump == JUMPTOMAIN) {
                                                mView.loginSuccees();
                                            } else if (jump == JUMPTOLOGIN) {
                                                mView.jumpToLogin();
                                            }
                                        }
                                    })
                                    .show();
                        }
                )
                .callback(permission)
                .start();
    }

    @Override
    public void doAutoLogin() {
        if (!SpUtil.getString(AppConfig.getInstance().getApplicationContext(), ContainValue.LOGINPHONE, "").equals("") && !SpUtil.getString(AppConfig.getInstance().getApplicationContext(), ContainValue.LOGINPASSWORD, "").equals("")) {
            Map<String, String> map = new HashMap<>();
            map.put("phone", SpUtil.getString(AppConfig.getInstance().getApplicationContext(), ContainValue.LOGINPHONE, ""));
            map.put("password", SpUtil.getString(AppConfig.getInstance().getApplicationContext(), ContainValue.LOGINPASSWORD, ""));
            Disposable disposable = httpAPIWrapper.userLogin(map)
                    .subscribe(new Consumer<UserLogin>() {
                        @Override
                        public void accept(UserLogin user) throws Exception {
                            KLog.i("onSuccesse");
                            ContainValue.userLogin = user;
                            getMyInfo(user.getData().getUserId() + "");
//                            getToken();
                            jump = JUMPTOMAIN;
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                            //onError
                            KLog.i("onError");
                            throwable.printStackTrace();
                            mView.closeProgressDialog();
                        }
                    }, new Action() {
                        @Override
                        public void run() throws Exception {
                            //onComplete
                            KLog.i("onComplete");
                        }
                    });
            mCompositeDisposable.add(disposable);
        }
    }

    @Override
    public void getLastVersion() {
        hasUpdate = false;
        //如果本地记录的应用版本和获取的应用版本不一致,就需要跳转到欢迎页面
        if (SpUtil.getInt(AppConfig.getInstance(), ContainValue.LOCALVERSIONCODE, 0) != VersionUtil.getAppVersionCode(AppConfig.getInstance())) {
            KLog.i("需要跳转到guest.........................");
            KLog.i(SpUtil.getInt(AppConfig.getInstance(), ContainValue.LOCALVERSIONCODE, 0));
            KLog.i(VersionUtil.getAppVersionCode(AppConfig.getInstance()));
            jumpToGuest = true;
        }
    }



    @Override
    public void getToken() {
        Map<String, String> map = new HashMap();
        map.put("uid", ContainValue.userLogin.getData().getUserId() + "");
        Disposable disposable = httpAPIWrapper.getImToken(map)
                .subscribe(new Consumer<Token>() {
                    @Override
                    public void accept(Token token) throws Exception {
                        //isSuccesse
                        KLog.i("onSuccesse");
                        mView.setToken(token.getData().getToken());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //onError
                        KLog.i("onError");
                        throwable.printStackTrace();
                        //mView.closeProgressDialog();
                        //ToastUtil.show(mActivity, mActivity.getString(R.string.loading_failed_1));
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //onComplete
                        KLog.i("onComplete");
                    }
                });
        mCompositeDisposable.add(disposable);
    }
    @Override
    public void getMyInfo(String uid) {
        Disposable disposable = httpAPIWrapper.getUserInfo(uid)
                .subscribe(new Consumer<UserInfo>() {
                    @Override
                    public void accept(UserInfo user) throws Exception {
                        //isSuccesse
                        KLog.i("onSuccesse");
                        //mView.closeProgressDialog();
                        ContainValue.loginUserInfo = user.getData();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        //onError
                        KLog.i("onError");
                        throwable.printStackTrace();
                        //mView.closeProgressDialog();
                        //ToastUtil.show(mActivity, mActivity.getString(R.string.loading_failed_1));
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //onComplete
                        KLog.i("onComplete");
                    }
                });
        mCompositeDisposable.add(disposable);
    }

    private PermissionListener permission = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // 权限申请成功回调。
            if (requestCode == 101) {
                permissionState = 0;
                if (timeOver) {
                    if (jumpToGuest) {
                        mView.iumpToGuest();
                        return;
                    }
                    if (jump == JUMPTOMAIN) {
                        mView.loginSuccees();
                    } else if (jump == JUMPTOLOGIN) {
                        mView.jumpToLogin();
                    }
                }
            }
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            if (requestCode == 101) {
                KLog.i("权限申请失败");
                permissionState = 1;
                ToastUtil.show(mActivity, "权限申请失败,app部分功能将无法使用!!!");
                if (timeOver) {
                    if (jumpToGuest) {
                        mView.iumpToGuest();
                        return;
                    }
                    if (jump == JUMPTOMAIN) {
                        mView.loginSuccees();
                    } else if (jump == JUMPTOLOGIN) {
                        mView.jumpToLogin();
                    }
                }
            }
        }
    };
}